/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import controller.AccountLogin;
import entities.Users;
import java.io.IOException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author QUY-THI
 */
@ManagedBean
@SessionScoped
public class LoginBean {

    private String username;
    private String password;
    private Users user;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }

    /**
     * Creates a new instance of LoginBean
     */
    public LoginBean() {
    }

    public String checkLogin() {
        AccountLogin acc = new AccountLogin();
        user = acc.login(username, password);
        if (user != null) {
            if (user.getStatus() == true) {
                if (user.getRoleID().getRoleID() == 1) {
                    return "admin/home.xhtml?faces-redirect=true";
                } else {
                    return "instruster/home.xhtml?faces-redirect=true";
                }
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Account is locked please contact admin !"));
                return "";
            }
        }
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Username or Password invalid !"));
        return "";
    }

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "../index.xhtml?faces-redirect=true";
    }

    public String getAutoRedirect() throws IOException {
        if (username == null || username.equals("")) {
            FacesContext context = FacesContext.getCurrentInstance();
            ((HttpServletResponse) context.getExternalContext().getResponse()).sendRedirect("../index.xhtml");
        }
        return "";
    }
}
